/**
 * Created by Mark_ren on 2016/10/13.
 * 若得势,不忘初衷
 */
var express = require('express');
var moment = require("moment");

var router = express.Router();
var co = require('co');
var seqModule = require('./createModules');
var seq = new seqModule();
var formidable = require('formidable');
var getIP = require('./getIP');


/**
 * 查询方法
 */
router.get('/getLive', function (req, res, next) {
    co(function() {
        var params = {};
        var paramT = {};
        var paramU = {};
        paramU["$gt"] = moment().format("YYYY-MM-DD HH:mm:ss");
        
        if(req.query.id != undefined){
            params["id"] = req.query.id;
        }
        params["closeTime"] = paramU;
        paramT["where"] = params;
		paramT["order"]=[["closeTime",'asc']];
        //console.log(moment().format("YYYY-MM-DD HH:mm:ss") );


        seq.metLiveModule.findAll(paramT).then(function (result) {
            res.json({"success": true, "result": result});
        });

    }).catch(function (e) {
        res.json({'success': false, 'msg': '查询失败'});
        console.log(e);
    })
});

/**
 * 后台列表页查询方法
 */
router.get('/getMETlist', function (req, res, next) {
    co(function() {
        var params = {};
        var paramT = {};
        var paramU = {};
        //模糊查询
        if(req.query.id != undefined){
            params["id"]=req.query.id;
        }
        if(req.query.liveTitle != undefined){
            paramU["$like"]="%"+req.query.liveTitle+"%";
            params["liveTitle"]=paramU;
        }
        paramT["where"] = params;
        //console.log(moment().format("YYYY-MM-DD HH:mm:ss") );
        paramT["order"]=[["startTime",'DESC']];
        if(req.query.page != undefined && req.query.rows !=undefined){
            paramT["offset"]=parseInt(req.query.page);
            paramT["limit"]=parseInt(req.query.rows);
        }
        seq.metLiveModule.findAndCountAll(paramT).then(function(result){
            res.json({"success":true,"page":req.query.page,"total":result.count,"result":result.rows});
        });

    }).catch(function (e) {
        res.json({'success': false, 'msg': '查询失败'});
        console.log(e);
    }) 
});

//添加MET直播方法
router.post('/addMETlive', function(req, res, next) {
    co(function () {
        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            //files = [],
            //fields = [];

            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                fields.is_ccdt = parseInt(fields.is_ccdt);
                fields.ccdtProject = parseInt(fields.ccdtProject);
                seq.metLiveModule.create(fields).then(function (results) {
                    res.redirect(getIP+'MET_Manage/liveRoomManage.html');
                });
            });
        }
    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});

//修改MET直播内容
router.post('/updateMetLive', function(req, res, next) {
    co(function () {
        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            //files = [],
            //fields = [];

            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                var paramsT={};
                paramsT.where = {"id":fields.id};
                delete fields.id;
                fields.is_ccdt = parseInt(fields.is_ccdt);
                fields.ccdtProject = parseInt(fields.ccdtProject);
                seq.metLiveModule.update(fields,paramsT).then(function (results) {
                    res.redirect(getIP+'MET_Manage/liveRoomManage.html');
                });
            });
        }
    }).catch(function(e) {
        res.json({'success':false,'msg':'修改失败'});
        console.log(e);
    })
});

//删除
router.get('/deleteNews', function(req, res, next) {
    co(function () {
        var params=req.query.params;
        var arr=params.split(",");
        var paramT=[arr];
        seq.metLiveModule.destroy({'where':{'id':paramT}}).then(function(results){
            res.json({"success":true,"msg":"删除成功","rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'删除失败'});
        console.log(e);
    })
});

module.exports = router;